package com.scalar.chiptrack.adaptor.sitime.sales;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.util.Calendar;
import java.util.Date;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 7 Jan, 2010
 * Time: 3:42:06 PM
 */
public class SalesAdaptor extends JobHandler implements AdaptorConstants
{

    private static final int    PORT            = 21;
    private static final String FTP_HOST        = "ftp.sitime.net";
    public  static final String ADAPTOR_NAME    = "SITIME_SALES_ADAPTOR";
    public static final String FILE_NAME_BACKLOG = "backlog";
    public static final String FILE_NAME_FG_PARTS = "FG_PARTS";
    private static final String FILE_EXTN       = ".xls";
    private String m_username           = null;
    private String m_password           = null;
    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;
    private int    m_adaptor_id         = -1;
    private String fileDate             = null;
    private int retryCount = 0;
    public SalesAdaptor() throws Exception
    {
        try
        {
            m_username = "scalarsoft";
            m_password = "lmjRdku8gd";
            m_dataOutputDir = ConfigManager.getSalesBacklogPortingFileDir();

            if (m_dataOutputDir != null)
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, "salesBacklog" );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading SiTime FTP Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new SalesAdaptor().execute();
    }

    public void execute() throws Exception
    {
        java.util.Date begDate = null;
        try
        {
            //Getting the last Run Adaptor file Date ( As we are Inserting in the new Adaptor run info in the Starting itself)
            fileDate   = AdaptorRunInfo.getAdaptorLastParsedFileDate( ADAPTOR_NAME );

            //When File Date is NULL Setting the File Date Back to 4 Days From Current Date
            if ( fileDate == null )
            {
            	Calendar cal = Calendar.getInstance();
                cal.add( Calendar.DAY_OF_MONTH, -4 );
                begDate = cal.getTime();
                fileDate = StringUtils.formatDateToString( begDate, "MM/dd/yyyy");
            }

            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader( VENDOR_NAME_SITIME, CONSTANT_ADAPTOR );

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            FTPClient ftp = login( FTP_HOST, PORT, m_username, m_password );
            log( "Successfully logged in to " + FTP_HOST );
            System.out.println( "Successfully logged in to " + FTP_HOST );
     	   	
            ftp.chdir("Master Part #");
            downloadFGPartsFile( ftp );
            ftp.chdir("..");
            ftp.chdir("Backlog");
            //To Down DownLoad the File To Local System at Specepied path
            downloadBacklogFiles( ftp );

            // Log out
            logout( ftp );
            log( "\nSuccessfully logged out from SiTime Ftp Site" );
            System.out.println( "\nSuccessfully logged out from SiTime FTP Site" );
        }
        catch ( Exception e )
        {
            //ReLogin
            retryCount ++;

            if (e.toString().indexOf("Connection reset") > -1  && retryCount < 2 )
            {
                AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
                execute();
            }
            else
            {
                AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
                AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
                System.out.println("Exception while trying to connect and read data from "+FTP_HOST +" site: " + e);
                e.printStackTrace();
                throw e;
            }
        }
    }
    /**
     *
     * @param host
     * @param port
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    private FTPClient login( String host, int port, String username, String password ) throws Exception
    {
        FTPClient ftp = new FTPClient( host, port );
        ftp.login( username, password );
        ftp.debugResponses( false );
        ftp.setType( FTPTransferType.BINARY );
        // active does not allows me connect to ftp site even any proxy lies in path.
        ftp.setConnectMode( FTPConnectMode.PASV );
        return ftp;
    }

   
    private void downloadBacklogFiles( FTPClient ftp ) throws Exception
   	{
	   String[] listings = ftp.dir();

       if ( ( listings == null ) || ( listings.length == 0 ) )
       {
           return;
       }

       byte[] buf                          = null;
       FileOutputStream fileOutputStream   = null;
       String         tempFileName         = null;
       Date 		  tempFileDate		   = null;
       Date 		  fileDate 			   = null;

       try
       {
    	   System.out.println( "\tDownloading Backlog File...." );

           for ( int i = 0; i < listings.length; i++ )
           {
               if ( (listings[i].toUpperCase()).startsWith( "BACKLOG" ) && listings[i].endsWith(FILE_EXTN_XLS))
               {
                   if ( tempFileName == null )
                   {
                       tempFileName = listings[i];
                       tempFileDate = ftp.modtime( tempFileName );
                       //System.out.println( tempFileName + "MOD TIME " + tempFileDate );
                   }
                   else
                   {
                        String fileName = listings[i];

                        fileDate = ftp.modtime( fileName );

                        if ( fileDate != null && tempFileDate != null )
                        {
                            if ( fileDate.compareTo( tempFileDate ) >= 0 )
                            {
                                tempFileName = listings[i];
                            }
                        }
                    }
               }
           }
           
           if (   tempFileName != null )
           {
               log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
               if ( m_adaptor_id > 0 )
               {
                   AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_XLS, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
               }
               buf = ftp.get( tempFileName );
               tempFileName = FILE_NAME_BACKLOG + "_" + tempFileName.substring(0, tempFileName.indexOf(".") ) + "_" + AdaptorUtils.getTimeAsString() + FILE_EXTN;
               fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
               fileOutputStream.write( buf );
               fileOutputStream.flush();
               tempFileName = null;
           }
       }
       catch ( Exception e )
       {
           log( "Exception while downloading......... " + e );
           throw e;
       }
       finally
       {
           if ( fileOutputStream != null )
           {
               try
               {
                   fileOutputStream.flush();
                   fileOutputStream.close();
               }
               catch ( IOException ignore )
               {
                   System.out.println("ignore = " + ignore);
               }
           }
       }
   }

   private void downloadFGPartsFile( FTPClient ftp ) throws Exception
   	{
	   String[] listings = ftp.dir();

       if ( ( listings == null ) || ( listings.length == 0 ) )
       {
           return;
       }

       byte[] buf                          = null;
       FileOutputStream fileOutputStream   = null;
       String         tempFileName         = null;
       Date 		  tempFileDate		   = null;
       Date 		  fileDate 			   = null;

       try
       {
    	   System.out.println( "\tDownloading FG PARTS File...." );

           for ( int i = 0; i < listings.length; i++ )
           {
               if ( (listings[i].toUpperCase()).startsWith( "MASTER LIST" ) && listings[i].endsWith(FILE_EXTN_XLS))
               {
                   if ( tempFileName == null )
                   {
                       tempFileName = listings[i];
                       tempFileDate = ftp.modtime( tempFileName );
                       //System.out.println( tempFileName + "MOD TIME " + tempFileDate );
                   }
                   else
                   {
                        String fileName = listings[i];

                        fileDate = ftp.modtime( fileName );

                        if ( fileDate != null && tempFileDate != null )
                        {
                            if ( fileDate.compareTo( tempFileDate ) >= 0 )
                            {
                                tempFileName = listings[i];
                            }
                        }
                    }
               }
           }

           if (   tempFileName != null )
           {
               log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
               if ( m_adaptor_id > 0 )
               {
                   AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_XLS, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
               }
               buf = ftp.get( tempFileName );
               tempFileName = FILE_NAME_FG_PARTS + "_" + tempFileName.substring(0, tempFileName.indexOf(".") ) + "_" + AdaptorUtils.getTimeAsString() + FILE_EXTN;
               fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
               fileOutputStream.write( buf );
               fileOutputStream.flush();
               tempFileName = null;
           }
       }
       catch ( Exception e )
       {
           log( "Exception while downloading......... " + e );
           throw e;
       }
       finally
       {
           if ( fileOutputStream != null )
           {
               try
               {
                   fileOutputStream.flush();
                   fileOutputStream.close();
               }
               catch ( IOException ignore )
               {
                   System.out.println("ignore = " + ignore);
               }
           }
       }
   }
   	
    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }
        try
        {
            ftp.quit();
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From SiTime FTP Site" + ignore );
            throw ignore;
        }
        ftp = null;
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
